#!/usr/bin/env python
#-*- coding: utf-8 -*-

import urllib2
import urllib
import re
import time
import sys
import os

NETWORKERROR='NC'

def log_2_file(content):
    fw=open('./wapQQ.log', 'a')
    fw.write("===start===="+os.linesep+content+os.linesep+"===end==="+os.linesep)
    fw.close()

class WAPFARM(object):
    def __init__(self, qq, pw):
        self.qq = qq
        self.pw = pw
        self.mkey = ''
        self.post_url = ''
        self.verify_post_url = ''

        self.extend = ''
        self.r_sid = ''
        self.sid = ''
        self.myuid=''
        self.farm_index_url=''
        self.one_key_harvest_url = ''
        self.all_farm_info_url = ''
        self.farm_one_key_url = ''
        self.clean_place_url = ''
        self.farm_friend_list_url = ''
        self.mc_friend_list_url = ''

        self.producing_list=[] #producing....
        self.is_max_exp = False

        #self.get_jsession()

        self.header = {'Q-UA':'KQB10_GA/100047&KMTT_2/200047&JV2&111311&MicroEmulator2.0&V2',
                  'Q-AUTH':'6485e2e09f43bb00dd38cbad06c4f06a9eec971b2751b3c1', # update 2010-06-23
                  #'Q-AUTH':'0a1fb2a92035df3cdd38cbad06c4f06a9eec971b2751b3c1', # update 2010-06-16
                  #'Q-AUTH':'f85f1e3186e8862e05cb65a4d471da9e677ba94691346d98', 
                  'Q-GUID':'173f93733afd4785b939e0760c870c40',
                  'User-Agent':'MicroEmulator-2.0',
                  'Accept':'text/vnd.wap.wml,application/vnd.wap.xhtml+xml, text/html, text/plain, application/xhtml+xml,image/*,audio/*,application/vnd.symbian.install,x-epoc/x-sisx-app,text/vnd.sun.j2me.app-descriptor,application/java, */*',
                  'Connection':'keep-alive'}

        #self.get_mkey()
        #self.get_code()

    def get_jsession(self):
        """
          每次按照QQ浏览器点击农场都会进入这个wap.3g.qq.com，
          但是实际上并不需要进行浏览这个页面，可以不使用该函数。
          保留在这里，方便以后tx对这里作文章。
        """
        url = 'http://wap.3g.qq.com/'
        header = {'User-Agent':'MicroEmulator-2.0',
                  'Host':'wap.3g.qq.com',
                  'Accept':'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2',
                  'Connection':'keep-alive'}
        req = urllib2.Request(url=url, headers=header)
        conn = urllib2.urlopen(req)
        #print str(conn.info())
        #print conn.read()

    def get_login_url(self):
        """
         获得登录的页面的url: login_url
        """

        url = "http://app19.z.qq.com/qzone_app/index.jsp?app=353"
        req = urllib2.Request(url=url, headers=self.header)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("获取不到登录页面！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("获取不到登录页面！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("获取不到登录页面！"+os.linesep+"原因:未知")
            return NETWORKERROR


        res = conn.read()

        login_url=''
        try:
            login_url = re.findall(r"ontimer=\"(.*)\">", res,re.M)[0]
        except:
            login_url=''
        #print login_url
        ###log_2_file(url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))
        return login_url

    def get_mkey(self, url):
        """
         得到mkey，和post用户名密码的目的url。
         mkey 在登录的时候需要POST给服务器的。

         url: 登录页面的URL
        
        """
        mkey=''

        self.header['Referer']='http://app19.z.qq.com/qzone_app/index.jsp?appid=353'
        req = urllib2.Request(url=url, headers=self.header)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("获取不到mkey页面！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("获取不到mkey页面！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("获取不到mkey页面！"+os.linesep+"原因:未知")
            return NETWORKERROR

        #print str(conn.info())
        res = conn.read()
        ###log_2_file(url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))
        #print res
        del self.header['Referer']

        try:
            self.post_url = re.findall(r"<go href=\"(.*)\" method=\"post\">", res,re.M)[0]
            mkey = re.findall(r"<postfield name=\"mkey\" value=\"(.*)\"/>", res,re.M)[0]
        except:
            mkey=''
        return mkey

    def get_code(self, mkey):
        """
          先POST: QQ，密码，mkey给服务器。
          如果POST的时候网络出错，返回：NETWORKERROR
          如果返回的数据包含有验证码，则获取验证码图片并返回True。
          如果返回的数据包没有验证码，则直接返回False. 

        """
        url = self.post_url
        post_data = urllib.urlencode({'qq':'%s'% self.qq,'pwd':'%s'% self.pw,'mkey':'%s'% mkey})
        self.header['Content-Type'] = 'application/x-www-form-urlencoded'
        self.header['Content-Length'] = '%s'% len(post_data)
        
        req = urllib2.Request(url=url, headers=self.header, data=post_data)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("POST,qq,密码过去给服务器时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("POST,qq,密码过去给服务器时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("POST,qq,密码过去给服务器时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR

        #print str(conn.info())
        res = conn.read()
        #print res
        ###log_2_file(url+os.linesep+str(self.header)+os.linesep+str(post_data)+os.linesep+str(conn.info())+str(res))

        del self.header['Content-Type']
        del self.header['Content-Length']
        try:
            code_url = re.findall(r"<img src=\"(.*)\" alt=\"验证码\"/><br/>", res, re.M)[0]
            #print code_url
            self.extend = re.findall(r"<postfield name=\"extend\" value=\"(.*)\"/>", res, re.M)[0]
            #print self.extend
            self.r_sid = re.findall(r"<postfield name=\"r_sid\" value=\"(.*)\"/>", res, re.M)[0]
            #print self.r_sid
            self.verify_post_url = re.findall(r"<go href=\"(.*)\" method=\"post\">", res, re.M)[0]
            #print self.verify_post_url
        except:
            return False

        url = code_url
        req = urllib2.Request(url=url, headers=self.header)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("获取验证码图片时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("获取验证码图片时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("获取验证码图片时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR
        #print str(conn.info())
        res = conn.read()
        ###log_2_file(url+os.linesep+str(self.header)+os.linesep+str(conn.info()))
        fobjw = open('./verify.gif', 'w')
        fobjw.write(res)
        fobjw.close()
        #self.verify = raw_input('verify:')
        return True


    def post_verify(self, verify):
        """
         将验证码POST给服务器,检查是否输入正确。
           成功则从返回的数据包的头部得到相关Cookies，并且返回True
           否则返回False
        """

        url = self.verify_post_url
        post_data = urllib.urlencode({'qq':'%s'% self.qq, 'extend':'%s'% self.extend,'r_sid':'%s'% self.r_sid,'nb':'1','modifySKey':'false','verify':'%s'% verify})
        self.header['Content-Type'] = 'application/x-www-form-urlencoded'
        self.header['Content-Length'] = '%s'% len(post_data)
        req = urllib2.Request(url=url, headers=self.header, data=post_data)

        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("POST验证码时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("POST验证码时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("POST验证码时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR
        #print str(conn.info())
        res = conn.read()
        ###log_2_file(url+os.linesep+str(self.header)+os.linesep+str(post_data)+os.linesep+str(conn.info())+str(res))
        #print res
        del self.header['Content-Type']
        del self.header['Content-Length']

        try:
            cookie_mzalc  = re.findall(r"Set-Cookie: mzalc=(.*);Path=/;Domain=.z.qq.com", str(conn.info()), re.M)[0]
            cookie_mqzone_lastLoginQq  = re.findall(r"Set-Cookie: mqzone_lastLoginQq=(.*);Path=/;Domain=.qq.com;", str(conn.info()), re.M)[0]
            qcookie_sid  = re.findall(r"Set-QCookie: qcookie_sid=(.*); domain=.qq.com;", str(conn.info()), re.M)[0]
        except:
            return False
        #print cookie_mzalc
        #print cookie_mqzone_lastLoginQq
        #print qcookie_sid
        self.header['Cookie'] = 'mzalc=%s; mqzone_lastLoginQq=%s'% (cookie_mzalc, cookie_mqzone_lastLoginQq)
        self.header['QCookie']= 'qcookie_sid=%s'% qcookie_sid
        #print self.header
        self.sid = re.findall(r"ontimer=\"(.*)\">", res, re.M)[0].split('?sid=')[1]
        #print self.sid
        return True

    def get_farm_index_url(self):
        """
         主要获得农场的主链接，变化的只有url中的appN --N: 1,2,3,...19
         可以直接访问app19这个主机。而不需要这个方法！
        """
        url = "http://app19.z.qq.com/qzone_app/index.jsp?appid=353&sid=%s"% self.sid
        req = urllib2.Request(url=url, headers=self.header)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("获取农场链接时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("获取农产链接时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("获取农产链接时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR
        #print str(conn.info())
        res = conn.read()
        ###log_2_file(url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))
        self.farm_index_url = re.findall(r"ontimer=\"(.*)\">", res,re.M)[0]
        #print self.farm_index_url
        return True

    def go_farm_index(self,is_first=False):
        """
        获得农场的主页面，并判断返回的数据包是否包含有 一键收获 字样，如果有就返回一键收获的url
        否则url为空。并返回False。
        并且判断是否为空地和枯萎作物，如果有任意一个，则设置所有获得所有作物信息的url为空。
        否则设置获得所有作物信息的url。

        参数is_first是用来标记是否为第一次获得该主页面，如果是服务器会返回一个cookie，需要保存并添加到头部。

        先
         设置: self.farm_friend_list_url
        再判断网络: 
           如果网络出错: 返回NETWORKERROR
           否则:
             判断self.farm_one_key_url是否为空:
                 如果不为空: 返回self.farm_one_key_url  一键收获自己的农作物
                 否则:
                   设置:
                      self.all_farm_info_url #有空地 和 枯萎 都设置为NULL
                      self.clean_place_url   #设置枯萎
                    返回:False

        """
        #url = self.farm_index_url
        url = "http://farm13.z.qq.com/farm/index.jsp?sid=%s&B_UID=%s"% (self.sid, self.qq)
        req = urllib2.Request(url=url, headers=self.header)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("获取农产页面时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("获取农场页面时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("获取农场页面时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR
        #print str(conn.info())
        res = conn.read()
        #print res
        ###log_2_file(url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))
        if is_first:
            #print "=====First to get cookie!======"
            cookie_mqzone_qqfarm = re.findall("Set-Cookie: mqzone_qqfarm=(.*);Path=/;Domain=.z.qq.com;", str(conn.info()), re.M)[0]
            tmp_cookie = self.header['Cookie']
            self.header['Cookie'] = tmp_cookie+";mqzone_qqfarm=%s"% cookie_mqzone_qqfarm

        self.farm_friend_list_url = re.findall(r"我的农场\|<a href=\"(.*)\">好友农场", res, re.M)[0]
        self.myuid = re.findall(r"myuid=(\d+)", res, re.M)[0]

        try:
            self.farm_one_key_url = re.findall(r"一键<a href=\"(.*)\">收获</a>", res, re.M)[0]
            #print self.farm_one_key_url
        except:
            self.farm_one_key_url = ''
        if self.farm_one_key_url != '':
            return self.farm_one_key_url
        else:
            try:
                self.all_farm_info_url = re.findall("<a href=\"(.*)\">查看更多不可操作土地>></a><br/>", res, re.M)[0]
                #print self.all_farm_info_url
            except:
                self.all_farm_info_url = ''
            if -1 != res.find('[空地]'):#暂时不支持播种
                self.all_farm_info_url = ''
            if -1 !=res.find('[枯萎的作物]'):#一键铲除铲除枯萎作物
                self.all_farm_info_url = ''
                if -1 != res.find('>铲除</a>'):
                    self.clean_place_url = re.findall(r"一键<a href=\"(.*)\">铲除", res, re.M)[0]
                    #print self.clean_place_url
                    #raw_input("enter to clean")

            return False

    def farm_get_can_steal_friends(self):
        url = self.farm_friend_list_url
        req = urllib2.Request(url=url, headers=self.header)
        conn = urllib2.urlopen(req)
        res = conn.read()
        #print res
        ###log_2_file(url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))
        if -1 == res.find('1.<anchor>'): #朋友里面没有可摘的
            return False
        can_steal_html = res.split("<anchor>")
        del can_steal_html[0]
        can_steal = [] #可偷列表
        for one in can_steal_html:
            one_friend = {} # 一个朋友 可以偷信息
            one_friend['url'] = re.findall(r"<go href=\"(.*)\" method=\"post\">", one,re.M)[0]
            one_friend['uid'] = re.findall(r"<postfield name=\"uid\" value=\"(.*)\"/>", one, re.M)[0]
            one_friend['B_UID'] = re.findall(r"<postfield name=\"B_UID\" value=\"(.*)\"/>", one, re.M)[0]
            one_friend['myuid'] = re.findall(r"<postfield name=\"myuid\" value=\"(.*)\"/>", one, re.M)[0]
            one_friend['money'] = re.findall(r"<postfield name=\"money\" value=\"(.*)\"/>", one, re.M)[0]
            one_friend['list'] = re.findall(r"<postfield name=\"list\" value=\"(.*)\"/>", one, re.M)[0]
            one_friend['pageNo'] = re.findall(r"<postfield name=\"pageNo\" value=\"(.*)\"/>", one, re.M)[0]
            one_friend['pos'] = re.findall(r"<postfield name=\"pos\" value=\"(.*)\"/>", one, re.M)[0]
            one_friend['next'] = re.findall(r"<postfield name=\"next\" value=\"(.*)\"/>", one, re.M)[0]
            one_friend['B_UID'] = re.findall(r"<postfield name=\"B_UID\" value=\"(.*)\"/>", one, re.M)[0]
            one_friend['nick'] = re.findall(r"</go>(.*)</anchor><br/>", one, re.M)[0]
            
            can_steal.append(one_friend)
            del one_friend
            #one_friend.clear()
        return can_steal

    def farm_steal_all_friends(self, can_steal_list):
        for steal in can_steal_list:
            url = "http://farm2.z.qq.com/farm/steal_all.jsp?sid=%s&B_UID=%s&uid=%s&myuid=%s&money=%s"% (self.sid, 
                    steal['B_UID'], steal['uid'], steal['myuid'], steal['money'])
            req = urllib2.Request(url=url, headers=self.header)
            conn = urllib2.urlopen(req)
            res = conn.read()
            #print url
            print "====您在\033[1;34m%s\033[0m的农场摘取情况:"% steal['nick']
            result = res.split("<br/>")[1].strip().replace('\r', '').replace('\n','')
            if result=='':
                print "什么也没摘到，或许你已经摘过了！"
            else:
                print result
            #print "==========================================================================\n"
        ###log_2_file(url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))

        


    def get_all_farm_info(self):
        """
        获得农场所有农作物的信息:土地号和对应的植物，对应植物的成熟时间。并将该信息列表返回。

        先判断获得所有农作物的url是否为空，如果不是才进行获取。
        """
        url = self.all_farm_info_url
        if url == '':
            return False

        req = urllib2.Request(url=url, headers=self.header)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("获取农作物信息时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("获取农作物信息时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("获取农作物信息时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR
        #print str(conn.info())
        res = conn.read()
        #print res
        ###log_2_file(url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))
        all_farm_info_html = res.split('刷新土地</a><br/>')[1].split('<a href=')[0].split('<br/>')
        all_farm_info = []
        for farm in all_farm_info_html:
            if farm.replace('\r', '').replace('\n','') != '':
                all_farm_info.append(farm.replace('\r', '').replace('\n',''))
        #for f in all_farm_info:
            #print f
        return all_farm_info

    def farm_one_key_clean(self):
        url = self.clean_place_url
        if url == '':
            return False
        req = urllib2.Request(url=url, headers=self.header)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("一键铲除枯萎作物时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("一键铲除枯萎作物时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("一键铲除枯萎作物时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR

        res = conn.read()
        #print res
        ###log_2_file(url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))
        result = res.split('<br/>')[1].replace('\r','').replace('\n', '').strip()
        if -1 != result.find('没有可铲除的土地'):
            result=''
        return result



    def farm_one_key_harvest(self, url):
        """
         一键 收获。url为一键收获的url地址。

           网络出错: 返回NETWORKERROR
           协议改变: 返回False
           正常收获: 返回结果(字符串)

        """
        #print url
        url="http://farm43.z.qq.com/farm/harvest_all.jsp?sid=%s&B_UID=%s&myuid=%s"% (self.sid, self.qq, self.myuid)
        req = urllib2.Request(url=url, headers=self.header)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("一键收获自己作物时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("一键收获自己作物时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("一键收获自己作物时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR
        #print str(conn.info())
        res = conn.read()
        #print res
        if -1 != res.find('http://vip.3g.qq.com/index.jsp'): #协议改变
            return False
        ###log_2_file(url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))
        result = res.split('<br/>')[1].replace('\r', '').replace('\n', '').strip()
        return result

    def farm_get_friends_list(self):
        url="http://farm35.z.qq.com/farm/friend_list_exp.jsp?sid=%s&myuid=%s"% (self.sid, self.myuid)
        req = urllib2.Request(url=url, headers=self.header)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("获取朋友列表时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("获取朋友列表时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("获取朋友列表时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR
        #print str(conn.info())
        res = conn.read()
        friends_info_list=[]

        page=1
        while (-1!=res.find('下页')):
            page=page+1
            friends = res.replace('\r','').replace('\n','').split('.<a href=')
            del friends[0]
            for friend in friends:
                friend_dict={}
                friend_dict['nick']=re.findall(r">(.*)</a>",friend, re.M)[0].split('</a><br/>')[0]
                friend_dict['B_UID']=re.findall(r"B_UID=(\d+)", friend, re.M)[0]
                friend_dict['uid']=re.findall(r"uid=(\d+)", friend, re.M)[0]
                friend_dict['money']=re.findall(r"money=(\d+)", friend, re.M)[0]
                friends_info_list.append(friend_dict)
                del friend_dict
            url="http://farm2.z.qq.com/farm/friend_list_exp.jsp?sid=%s&myuid=%s&pageNo=%s"% (self.sid, self.myuid, page)
            req = urllib2.Request(url=url, headers=self.header)
            try:
                conn = urllib2.urlopen(req)
            except:
                break
            res = conn.read()

        # last page
        friends = res.replace('\r','').replace('\n','').split('.<a href=')
        del friends[0]
        for friend in friends:
            friend_dict={}
            friend_dict['nick']=re.findall(r">(.*)</a>",friend, re.M)[0].split('</a><br/>')[0]
            friend_dict['B_UID']=re.findall(r"B_UID=(\d+)", friend, re.M)[0]
            friend_dict['uid']=re.findall(r"uid=(\d+)", friend, re.M)[0]
            friend_dict['money']=re.findall(r"money=(\d+)", friend, re.M)[0]
            friends_info_list.append(friend_dict)
            del friend_dict
            
        return friends_info_list

    def farm_steal_friend(self, friend):
        url = "http://farm2.z.qq.com/farm/steal_all.jsp?sid=%s&B_UID=%s&uid=%s&myuid=%s&money=%s"% (self.sid, 
                friend['B_UID'], friend['uid'], self.myuid, friend['money'])
        req = urllib2.Request(url=url, headers=self.header)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("偷取朋友作物时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("偷取朋友作物时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("偷取朋友作物时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR
        res = conn.read()
        result = res.split("<br/>")[1].strip().replace('\r', '').replace('\n','')
        return result

    def farm_one_key_plant(self, crop_id, red):
        url="http://farm39.z.qq.com/farm/seed_all.jsp?sid=%s&cid=%d&B_UID=%s&myuid=%s&isplant=1&red=%d&c=0&seedno=100&index=1"% (self.sid,
                crop_id, self.qq, self.myuid, red)
        req = urllib2.Request(url=url, headers=self.header)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("播种作物时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("播种作物时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("播种作物时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR
        res = conn.read()
        #print res
        result=''
        try:
            result=res.split('好友农场</a><br/>')[1].split('<br/>')[0].replace('\r','').replace('\n','')
        except:
            result=''
        return result

        


    def go_mc_index(self):
        """牧场 首页
           先判断协议是否改变，如果改变返回False
           如果没有改变，返回一键收获的URL。
             如果存在可以一键收获，则返回URL
             否则返回空的URL
        """

        url = "http://mc4.z.qq.com/mc/main.jsp?B_UID=%s&sid=%s"% (self.qq, self.sid)
        req = urllib2.Request(url=url, headers=self.header)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("获取牧场首页时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("获取牧场首页时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("获取牧场首页时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR
        #print str(conn.info())
        res = conn.read()
        #print res
        ###log_2_file("牧场首页"+os.linesep+url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))
        if -1 != res.find('<card id="err-203"'):# TX浏览器的协议改变了 很可能是Q-AUTH 的值变
            return False
        self.mc_friend_list_url = re.findall(r"我的牧场\|<a href=\"(.*)\">好友牧场", res, re.M)[0]
        try:
            mc_one_key_harvest_url = re.findall(r"一键<a href=\"(.*)\">收获</a>", res, re.M)[0]
            #print mc_one_key_harvest_url
        except:
            mc_one_key_harvest_url = ''
        return mc_one_key_harvest_url

    def mc_one_key_harvest(self):
        """牧场一键收获"""
        url = "http://mc4.z.qq.com/mc/op.jsp?sid=%s&B_UID=%s&p=5&m=-8&op=1"% (self.sid, self.qq)
        req = urllib2.Request(url=url, headers=self.header)

        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("牧场一键收获时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("牧场一键收获时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("牧场一键收获时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR
            
        res = conn.read()
        post_data=self.check_need_verify(res)
        if post_data['need']:
            os.system('mplayer contact.wav')
            url=url.split('?')[0]
            post_data['iv_verify']=raw_input("verify:")
            post_data['sid'] = self.sid
            post_data['B_UID'] = self.qq
            post_data['p'] = 5
            post_data['m'] = '-8'
            post_data['op'] = '1'
            del post_data['need']
            print post_data
            encode_data=urllib.urlencode(post_data)         
            #url = "http://mc4.z.qq.com/mc/op.jsp"
            req = urllib2.Request(url=url, headers=self.header, data=encode_data)
            conn = urllib2.urlopen(req)
            res=conn.read()
            #print url
            print encode_data
            #print str(conn.info())

        #print res
        ###log_2_file("牧场一键收获"+os.linesep+url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))
        result=''
        try:
            result=res.split('好友牧场</a><br/>')[1].split('【可操作的动物及产品】<br/>')[0].replace('\r','').replace('\n','').replace('<br/>',os.linesep)
        except:
            result=''
            log_2_file("牧场一键收获"+os.linesep+url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))
        return result


    def mc_get_can_steal_friends(self):
        url=self.mc_friend_list_url
        #http://mc4.z.qq.com/mc/friends.jsp?sid=P4lP8igC3P2kXW1x6I+CxQ==&B_UID=80068187&op=1
        req = urllib2.Request(url=url, headers=self.header)
        conn = urllib2.urlopen(req)
        #print str(conn.info())
        res = conn.read()
        #print res
        ###log_2_file("牧场朋友页面"+os.linesep+url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))
        is_more=False
        if -1 != res.find("1.<a href="):
            steal_list=[]
            html = res.split("1.<a href=")[1].split("</p>")[0].split("<br/>")
            html[0]="<a href="+html[0]
            html_len=len(html)
            if html_len>10: #多页
                for i in xrange(html_len-10):
                    #print i
                    del html[html_len-i-1] #先要前面十个 多于10个，还没解决。
                is_more=True
            else:
                del html[html_len-1]
            for one in html:
                #print one
                steal_dict={}
                steal_dict['nick']=re.findall(r">(.*)</a>",one, re.M)[0]
                #steal_dict=['url'] = re.findall(r".<a href=\"(.*)\">",one, re.M)[0].replace("index.jsp", "op.jsp").replace('amp;','').replace('s=0','')+"&p=2&a=1&op=1"
                steal_dict['B_UID']=re.findall(r"&amp;B_UID=(.*)&amp;", one, re.M)[0]
                steal_dict['m']=re.findall(r"&amp;m=(.*)&amp;", one, re.M)[0]
                steal_list.append(steal_dict)
                del steal_dict
            return steal_list
        else: #好友里面没有东西可偷
            return False

    def mc_steal_friend(self,steal_dict):
        url="http://mc4.z.qq.com/mc/op.jsp?sid=%s&B_UID=%s&p=2&a=1&m=%s&op=1"% (self.sid, steal_dict['B_UID'], steal_dict['m'])
        req = urllib2.Request(url=url, headers=self.header)
        result=''
        
        try:
            conn = urllib2.urlopen(req)
        except:
            result="网络问题!"
            return result
        #print str(conn.info())
        res = conn.read()
        post_data=self.check_need_verify(res)
        if post_data['need']:
            os.system('mplayer contact.wav')
            url=url.split('?')[0]
            post_data['iv_verify']=raw_input("verify:")
            post_data['sid'] = self.sid
            post_data['B_UID'] = steal_dict['B_UID']
            post_data['p'] = 2
            post_data['a'] = 1
            post_data['m'] = steal_dict['m']
            post_data['op'] = '1'
            del post_data['need']
            print post_data
            encode_data=urllib.urlencode(post_data)         
            #url = "http://mc4.z.qq.com/mc/op.jsp"
            req = urllib2.Request(url=url, headers=self.header, data=encode_data)
            conn = urllib2.urlopen(req)
            res=conn.read()
            #print url
            print encode_data
            #print str(conn.info())
        #print res
        #log_2_file("偷取页面"+steal_dict['nick']+os.linesep+url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))
        if -1 != res.find('<card id="err-1004"'):
            if -1 != res.find('此好友已经没有可操作的动物及产品，去其他好友牧场看看吧'):
                result="手下留情，给主人留一点吧!"
            else:
                result="手下留情，给主人留一点吧。这个家伙的牧场有生产期的动物，程序将自动将它赶去生产。"
                if self.is_max_exp:
                    print "经验达到每天最高值, 依然将动物抓去生产!"
                    result = self.mc_produce(steal_dict)
                else:
                    result = self.mc_produce(steal_dict)
        elif -1 != res.find('<br/>【可操作的动物及产品】<br/>'):
            #self.mc_produce(steal_dict)
            result=res.split('好友牧场</a><br/>')[1].split('<br/>【可操作的动物及产品】<br/>')[0].replace('\r','').replace('\n','').replace('<br/>','')
        else:
            try:
                result=res.split('好友牧场</a><br/>')[1].split('【可操作牧场】<br/>')[0].replace('\r','').replace('\n','').replace('<br/>','').replace('此好友已经没有可操作的动物及产品，去其他好友牧场看看吧。', '')
            except:
                result="\033[1;31m需要验证码??\033[0m"
                print res
        return result

    def mc_produce(self, who_dict):
        url="http://mc4.z.qq.com/mc/op.jsp?sid=%s&B_UID=%s&p=1&a=1&m=%s&op=1"% (self.sid, who_dict['B_UID'], who_dict['m'])
        req = urllib2.Request(url=url, headers=self.header)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("牧场抓去生产时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("牧场抓去生产时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("牧场抓去生产时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR
        #print str(conn.info())
        res = conn.read()
        #print res
        ###log_2_file("生产页面"+os.linesep+url+os.linesep+str(self.header)+os.linesep+str(conn.info())+str(res))
        result=''
        if -1 != res.find('<card id="err-1002"'):
            result="下手太慢，动物已经被赶去生产了。或者该动物为收获期!"
        if -1 != res.find('<card id="op"'):
            result=res.split('好友牧场</a><br/>')[1].split('<br/>')[0].replace('\r','').replace('\n','')
            self.add_producing(who_dict)
            del who_dict
            if -1 != result.find('您已加满'):
                self.is_max_exp = True
        return result

    def mc_get_friends_list(self):
        url="http://mc4.z.qq.com/mc/friends.jsp?sid=%s&B_UID=%s&op=0"% (self.sid, self.qq)
        req = urllib2.Request(url=url, headers=self.header)
        try:
            conn = urllib2.urlopen(req)
        except urllib2.URLError, e:
            log_2_file("牧场获取朋友列表时出错！"+os.linesep+"原因:e.reason"+str(e.reason))
            return NETWORKERROR
        except urllib2.HTTPError, e:
            log_2_file("牧场获取朋友列表时出错！"+os.linesep+"原因:e.code"+str(e.code))
            return NETWORKERROR
        except:
            log_2_file("牧场获取朋友列表时出错！"+os.linesep+"原因:未知")
            return NETWORKERROR
        #print str(conn.info())
        res = conn.read()
        friends_info_list=[]

        page=1
        while (-1!=res.find('下页')):
            page=page+1
            friends = res.replace('\r','').replace('\n','').split('.<a href=')
            del friends[0]
            for friend in friends:
                friend_dict={}
                friend_dict['nick']=re.findall(r">(.*)</a>",friend, re.M)[0].split('</a><br/>')[0]
                friend_dict['B_UID']=re.findall(r"B_UID=(\d+)", friend, re.M)[0]
                friend_dict['m']=re.findall(r"m=(\d+)", friend, re.M)[0]
                friends_info_list.append(friend_dict)
                del friend_dict
            url="http://mc4.z.qq.com/mc/friends.jsp?sid=%s&B_UID=%s&op=0&pageNo=%d"% (self.sid, self.qq, page)
            req = urllib2.Request(url=url, headers=self.header)
            try:
                conn = urllib2.urlopen(req)
            except:
                print "获取朋友列表异常,朋友类表将不完整!可能是网络问题!"
                break
            res = conn.read()

        # last page
        friends = res.replace('\r','').replace('\n','').split('.<a href=')
        del friends[0]
        for friend in friends:
            friend_dict={}
            friend_dict['nick']=re.findall(r">(.*)</a>",friend, re.M)[0].split('</a><br/>')[0]
            friend_dict['B_UID']=re.findall(r"B_UID=(\d+)", friend, re.M)[0]
            friend_dict['m']=re.findall(r"m=(\d+)", friend, re.M)[0]
            friends_info_list.append(friend_dict)
            del friend_dict
            
        return friends_info_list



    def get_friend_info(self, friend):
        url="http://mc4.z.qq.com/mc/index.jsp?sid=%s&B_UID=%s&op=0&m=%s"% (self.sid, friend['B_UID'], friend['m'])
        req = urllib2.Request(url=url, headers=self.header)
        conn = urllib2.urlopen(req)
        #print str(conn.info())
        res = conn.read()
        animal = res.split('<!-- 动物崽和动物 -->')[1]

        return res
    def check_need_verify(self,res):
        post_data={}
        if -1 != res.find('<card id="DIVCard" title="验证码验证">'):
            url=re.findall(r"<img src=\"(.*)\" alt=\"\"/><br/>", res, re.M)[0]
            post_data['need']=True
            post_data['r_sid'] = re.findall(r"<postfield name=\"r_sid\" value=\"(.[^>]*)\"/>", res, re.M)[0]
            post_data['bid'] = re.findall(r"<postfield name=\"bid\" value=\"(.[^>]*)\"/>", res, re.M)[0]
            req=urllib2.Request(url=url, headers=self.header)
            conn = urllib2.urlopen(req)
            print str(conn.info())
            res = conn.read()
            fobjw = open('./verify.gif', 'w')
            fobjw.write(res)
            fobjw.close()
        else:
            post_data['need']=False

        return post_data

    def add_producing(self, who_dict):
        self.producing_list.append(who_dict)

    def mc_get_producing(self):
        return self.producing_list

    def mc_clean_producing(self):
        self.producing_list=[]




def mc_handle(wapfarm):
    mc_one_key_harvest_url = wapfarm.go_mc_index()
    if NETWORKERROR == mc_one_key_harvest_url:
        print "\033[1;31m网络错误，请检查网络情况!\033[0m"
    elif False == mc_one_key_harvest_url:
        print "\033[1;31;47m协议已经改变，请更新程序后再使用!\033[0m"
        print "程序退出"
        sys.exit(1)
    elif mc_one_key_harvest_url != '':
        result = wapfarm.mc_one_key_harvest()
        if result == NETWORKERROR:
            print "\033[1;31m网络错误，请检查网络情况!\033[0m"
        elif result=='':
            print "可能协议改变了，请退出程序！联系\033[1;4;34mstuyorks@gmail.com\033[0m"
        else:
            print result

    else:
        print "牧场: 暂时没有动物可收获"
    print "现在去朋友那里看看! 试着将整个朋友都偷一遍!"
    #steal_list = wapfarm.mc_get_can_steal_friends()
    friends = wapfarm.mc_get_friends_list()
    if NETWORKERROR==friends:
        print "\033[1;31m网络错误，请检查网络情况!\033[0m"
    elif friends:
        for friend in friends:
            print "在\033[1;34m%s\033[0m牧场的情况:"% friend['nick']
            steal_result=wapfarm.mc_steal_friend(friend)
            print steal_result
            print 
        print "共%d个好友，已经扫描完毕!"% len(friends)
    else:
        print "朋友里面暂时没有东东可偷"

    producing_list=wapfarm.mc_get_producing()
    if producing_list:
        print "15秒后偷取刚刚抓去生产的动物!"
        time.sleep(15)#15秒后生产完毕
        for produced in producing_list:
            print "在\033[1;34m%s\033[0m牧场的情况:"% produced['nick']
            steal_result=wapfarm.mc_steal_friend(produced)
            print steal_result
            print
        wapfarm.mc_clean_producing()
    else:
        pass

    print "偷取朋友牧场完毕"


def print_page_not_found():
        print "\033[1;31m访问的页面不存在，程序需要更新！\033[0m"
        print "请更新程序后再重试！报告错误:\033[1;4;34mstuyorks@gmail.com\033[0m"
        print "程序退出!"

def login():
    qq = raw_input("QQ号码:")
    import getpass
    pw = getpass.getpass("密码:")
    wap_farm = WAPFARM(qq, pw)
    login_url = wap_farm.get_login_url()
    if login_url == NETWORKERROR:
        print "\033[1;31m网络错误，请检查网络情况，程序退出！\033[0m"
        sys.exit(1)
    if login_url == '':
        print_page_not_found()
        sys.exit(1)
    mkey = wap_farm.get_mkey(login_url)
    if mkey == NETWORKERROR:
        print "\033[1;31m网络错误，请检查网络情况，程序退出！\033[0m"
        sys.exit(1)
    if mkey == '':
        print_page_not_found()
        sys.exit(1)
    is_need_verify = wap_farm.get_code(mkey)
    if is_need_verify == NETWORKERROR:
        print "\033[1;31m网络错误，请检查网络情况，程序退出！\033[0m"
        sys.exit(1)
    if is_need_verify:
        verify = raw_input('请输入验证码:')
        isok = wap_farm.post_verify(verify)
        if isok == NETWORKERROR:
            print "\033[1;31m网络错误，请检查网络情况，程序退出！\033[0m"
            sys.exit(1)
        elif not isok:
            print "验证码或者密码错误，程序现在退出，请重新启动程序!"
            sys.exit(1)
        else:
            print "\033[1;5m登录成功!\033[m"
    else:
        print "\033[1;5m登录成功!\033[m"

    farm_one_key_url = wap_farm.go_farm_index(is_first=True)
    
    while farm_one_key_url == NETWORKERROR:
        print "\033[1;31m网络错误，请检查网络情况\033[0m"
        print "10秒后程序将自动重试...."
        time.sleep(10)
        farm_one_key_url = wap_farm.go_farm_index(is_first=True)

    return wap_farm


def farm_handle(wap_farm):
    t=10*60 #10 分钟扫描一次
    farm_one_key_url = wap_farm.go_farm_index(is_first=False)
    if farm_one_key_url: #可以一键收获
        result = wap_farm.farm_one_key_harvest(farm_one_key_url)
        if result==False:
            print "\033[1;31m协议改变，请更像程序再使用!\033[0m"
            print "程序退出!"
            sys.exit(1)
        elif result==NETWORKERROR:
            print "\033[1;31m网络错误，请检查网络情况\033[0m"
            print "程序放弃收获，请自己手动去收获!"
        else:
            print result
            is_clean = wap_farm.farm_one_key_clean() #铲除枯萎作物
            if is_clean==NETWORKERROR:
                print "\033[1;31m网络错误，请检查网络情况\033[0m"
                print "程序放弃铲除枯萎，请自己去铲除枯萎作物"
            elif is_clean:
                print is_clean
                print "铲除枯萎作物完毕!"
            else:
                pass
    else:
        print "农场还没有可以收获的作物"
        is_clean = wap_farm.farm_one_key_clean() #铲除枯萎作物
        if is_clean==NETWORKERROR:
            print "\033[1;31m网络错误，请检查网络情况\033[0m"
            print "程序放弃铲除枯萎，请自己去铲除枯萎作物"
        elif is_clean:
            print is_clean
            print "铲除枯萎作物完毕!"
        else:
            pass

    all_farm_info = wap_farm.get_all_farm_info() #获取农田信息
    print "农场土地信息如下:"
    if all_farm_info==False:
        print "农田有空地,现在程序将自动播种牧草!"
        plant_res = wap_farm.farm_one_key_plant(40, red=0)

        if plant_res==NETWORKERROR:
            print "\033[1;31m网络错误，请检查网络情况\033[0m"
            print "\033[1;31m播种失败!\033[0m"
        elif plant_res=='':
            print "\033[1;31m播种失败!　未知原因!\033[0m"
        else:
            print plant_res

    elif all_farm_info==NETWORKERROR:
        print "\033[1;31m网络错误，请检查网络情况\033[0m"
        print "农田信息获取失败!"
    else:
        for f in all_farm_info:
            print f
        
        #获取最先成熟的剩余时间
        if -1 != all_farm_info[1].find('小时'):
            hour = int(all_farm_info[1].split('小时')[0])
            min = int(all_farm_info[1].split('小时')[1].split('分')[0])
            sec = 0
        else:
            hour = 0
            if -1 != all_farm_info[1].find('分'):
                min = int(all_farm_info[1].split('分')[0])
                sec = 0
            else:
                min = 0
                sec = int(all_farm_info[1].split('秒')[0])
        t = hour*3600 + min*60 + sec #最先成熟时间
        ISOTIMEFORMAT='%Y-%m-%d %X'
        time_now = time.strftime(ISOTIMEFORMAT,time.localtime())
        print time_now+":最先成熟的农作物需要\033[1;31m%d\033[0m小时\033[1;31m%d\033[0m分钟\033[1;31m%d\033[0m秒后才成熟！"% (hour, min, sec)

    friends = wap_farm.farm_get_friends_list() #获取朋友列表
    if friends==NETWORKERROR:
        print "\033[1;31m网络错误，请检查网络情况\033[0m"
        print "\033[1;31m获取好友列表失败!\033[0m"
    elif friends:
	print "现在转去好友那里看看!"
        print "试着将朋友列表都偷一遍"
        for friend in friends:
            print "您在\033[1;34m%s\033[0m的农场摘取情况:"% friend['nick']            
            result = wap_farm.farm_steal_friend(friend)
            if result==NETWORKERROR:
                print "\033[1;31m网络错误，请检查网络情况\033[0m\n"
                print "\033[1;31m偷不到他的!\033[0m\n"
            elif result=='':
                print "什么也没捞到!该农场所剩无几或者没作物可以收获!\n"
            else:
                print result
                print 
        print "共%d个好友，已经扫描完毕!"% len(friends)
    else:
        print "获取不到好友列表!"
    return t



def main():
    wap_farm = login()
    while True:
        print "=======农场情况如下========="
        t = farm_handle(wap_farm)
        print "========End 农场============\n"
        print "=====牧场情况如下:=========="
        mc_handle(wap_farm) 
        print "========End 牧场============\n"
        ISOTIMEFORMAT='%Y-%m-%d %X'
        time_now = time.strftime(ISOTIMEFORMAT,time.localtime())
        print time_now
        if t > (10*60):
            print "\033[1;5m农作物最先成熟的时间大于10分钟，程序将在10分钟后再次扫描农牧场!\033[0m"
            time.sleep(10*60)
        else:
            print "\033[1;5m休息%d秒后,程序将再次扫描农牧场！\033[0m"% t
            time.sleep(t)
    

if __name__ == "__main__":
    main()
